package com.xbongbong.pro.statistic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.google.common.collect.Maps;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.FieldAttrConstant;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.enums.UnitEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.applist.pojo.vo.ListAppVO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.errorcodes.StatisticsServicesErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.service.toolbox.statistic.help.ChartDtoHelp;
import com.xbongbong.pro.service.toolbox.statistic.help.ThroughHelp;
import com.xbongbong.pro.service.toolbox.statistic.help.ThroughProService;
import com.xbongbong.pro.statistic.enums.ResultFromEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.factory.ChartStrategyFactory;
import com.xbongbong.pro.statistic.manager.feign.PaasFormFeignClient;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.pojo.IndexThroughPojo;
import com.xbongbong.pro.statistic.result.pojo.TitlePojo;
import com.xbongbong.pro.statistic.service.ResultThroughService;
import com.xbongbong.pro.statistic.through.pojo.ResultThroughPojo;
import com.xbongbong.pro.statistic.through.pojo.TableDataInfoPojo;
import com.xbongbong.pro.statistic.through.pojo.dto.ResultThroughDTO;
import com.xbongbong.pro.statistic.through.pojo.vo.IndexThroughDTO;
import com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.CompanyStructTypeEnum;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zcp
 * @version v1.0
 * @date 2019/4/26 14:12
 * @since v1.0
 */
@Service("resultThroughService")
public class ResultThroughServiceImpl implements ResultThroughService {
    private static final Logger LOG = LoggerFactory.getLogger(ResultThroughServiceImpl.class);
    @Resource
    private ChartDtoHelp chartDtoHelp;
    @Resource
    private ThroughHelp throughHelp;
    @Resource
    private PaasFormFeignClient paasFormFeignClient;
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private ChartStrategyFactory chartStrategyFactory;

    @Override
    public ResultThroughVO chartResultThrough(ResultThroughDTO resultThroughDTO) throws XbbException {
        return getResultThroughVo(resultThroughDTO, ResultFromEnum.WEB);
    }

    @Override
    public ResultThroughVO chartMobileResultThrough(ResultThroughDTO resultThroughDTO) throws XbbException {
        return getResultThroughVo(resultThroughDTO, ResultFromEnum.APP);
    }

    /**
     * 得到穿透结果并封装返回
     * @param resultThroughDTO 请求参数dto
     * @param resultFromEnum 统计请求来源枚举
     * @return com.xbongbong.pro.statistic.through.pojo.vo.ResultThroughVO
     * @throws XbbException
     * @author zcp
     * @date 2019/5/11 20:37
     * @since v1.0
     * @version v1.0
     */
    private ResultThroughVO getResultThroughVo(ResultThroughDTO resultThroughDTO, ResultFromEnum resultFromEnum) throws XbbException {

        // 判断是否是自定义指标
        if (Objects.equals(resultThroughDTO.getStatisticsType(),StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())){
            return getThroughList4Performance(resultThroughDTO,resultFromEnum);
        }

        //sCode、id必须传一个（用sCode判断是否为系统指标穿透）
        String systemCode = resultThroughDTO.getSystemCode();
        SystemCodeEnum systemCodeEnum = SystemCodeEnum.getByCode(systemCode);
        if (systemCodeEnum == null) {
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224055);
        }
        UserEntity userEntity = BeanUtil.copyProperties(resultThroughDTO.getLoginUser(), UserEntity.class, false);
        ResultThroughPojo resultThroughPojo = chartDtoHelp.getThroughPojo(userEntity, resultThroughDTO, systemCodeEnum);
        //查询数据，封装结果
        ThroughProService throughProService = chartStrategyFactory.getThroughProService(systemCodeEnum.getXbbRefTypeEnum().getCode());
        if (Objects.isNull(throughProService)){
            throughProService = chartStrategyFactory.getThroughProService(BasicConstant.ZERO);
        }
        ResultThroughVO resultThroughVo = throughProService.getThroughList(resultFromEnum, systemCodeEnum, resultThroughPojo, resultThroughDTO);
        resultThroughVo.setAvatar(resultThroughPojo.getAvatar());
        resultThroughVo.setName(resultThroughPojo.getName());

        return resultThroughVo;
    }

    /**
     *  获取自定义目标穿透结果vo
     * @param resultThroughDTO 穿透DTO对象
     * @param resultFromEnum 请求来源标识
     * @return 返回到前端的vo对象
     */
    private ResultThroughVO getThroughList4Performance(ResultThroughDTO resultThroughDTO, ResultFromEnum resultFromEnum) throws XbbException {
        ResultThroughVO resultThroughVO = new ResultThroughVO();
        // feign调用自定义指标的穿透解析
        String result = paasFormFeignClient.customChartResultThrough(resultThroughDTO, LocaleContextHolder.getLocale().toString());
        // 反序列化
        XbbResponse<IndexThroughDTO> xbbResponse = JSON.parseObject(result, new TypeReference<XbbResponse<IndexThroughDTO>>() {}, Feature.OrderedField);
        // 得到具体的穿透数据
        IndexThroughDTO indexThroughDTO = xbbResponse.getResult();
        ChartEntity chartEntity = chartCustomModel.getByKey(resultThroughDTO.getId(), resultThroughDTO.getCorpid());

        // 属性赋值：表头  处理自定义表头（表头字段和自定义设置的表头字段取交集）
        List<FieldAttrEntity> headList = indexThroughDTO.getHeadList();
        JSONArray penetrateAttrArr = chartEntity.getPenetrateAttr();
        // 如果有自定义穿透属性则显示自定义属性，如果没有自定义穿透属性则显示默认“考核指标”，“归属人”，“统计日期”
        Map<String, JSONObject> penetrateAttrMap = null;
        if (CollectionsUtil.isNotEmpty(penetrateAttrArr)) {
            // 分为pc端和app端分别处理，pc端有多少个表头就展示多少个表头，app端是最多显示6个表头
            if (Objects.equals(resultFromEnum,ResultFromEnum.WEB)){
                penetrateAttrMap = new HashMap<>(Maps.newHashMapWithExpectedSize(penetrateAttrArr.size()));
                for (Object penetrateAttr : penetrateAttrArr) {
                    JSONObject penetrateAttrObj = penetrateAttr instanceof JSONObject ? (JSONObject) penetrateAttr : null;
                    if (penetrateAttrObj == null) {
                        continue;
                    }
                    String attr = FastJsonHelper.getStringOrDefault(penetrateAttrObj, StringConstant.ATTR, "");
                    penetrateAttrMap.put(attr, penetrateAttrObj);
                }
            }else if (Objects.equals(resultFromEnum,ResultFromEnum.APP)){
                penetrateAttrMap = new HashMap<>(Maps.newHashMapWithExpectedSize(Constant.SIX));
                int penetrateAttrMapNum = 0;
                for (Object penetrateAttr : penetrateAttrArr) {
                    JSONObject penetrateAttrObj = penetrateAttr instanceof JSONObject ? (JSONObject) penetrateAttr : null;
                    if (penetrateAttrObj == null || penetrateAttrMapNum > Constant.FIVE) {
                        continue;
                    }
                    String attr = FastJsonHelper.getStringOrDefault(penetrateAttrObj, StringConstant.ATTR, "");
                    penetrateAttrMap.put(attr, penetrateAttrObj);
                    penetrateAttrMapNum++;
                }
            }

        } else {
            penetrateAttrMap = new HashMap<>(Maps.newHashMapWithExpectedSize(Constant.SCALE));
            JSONObject sourceAttrObj = chartEntity.getSourceAttr();
            JSONObject belongAttrObj = chartEntity.getBelongAttr();
            JSONObject timeAttrObj = chartEntity.getTimeAttr();
            String sourceAttr = FastJsonHelper.getStringOrDefault(sourceAttrObj, StringConstant.ATTR, "");
            String belongAttr = FastJsonHelper.getStringOrDefault(belongAttrObj, StringConstant.ATTR, "");
            String timeAttr = FastJsonHelper.getStringOrDefault(timeAttrObj, StringConstant.ATTR, "");
            penetrateAttrMap.put(sourceAttr, sourceAttrObj);
            penetrateAttrMap.put(belongAttr, belongAttrObj);
            penetrateAttrMap.put(timeAttr, timeAttrObj);
        }
        // 处理须返回的表头字段
        List<TitlePojo> titlePojoList = handleHeadList(headList, penetrateAttrMap);
        resultThroughVO.setTitle(titlePojoList);

        // 根据不同的请求来源，处理不同的业务,向resultThroughVO传入对应的参数
        switch (resultFromEnum){
            case WEB:
                handleSpecificData4Web(indexThroughDTO,penetrateAttrMap,resultThroughVO,chartEntity);
                break;
            case APP:
                handleSpecificData4App(indexThroughDTO,penetrateAttrMap,resultThroughVO);
                break;
            default:
                throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224022, StatisticsServicesErrorCodeEnum.API_ERROR_224022.getMsg(), I18nMessageUtil.getMessage(I18nStringConstant.IDENTIFY_TARGET_REQUEST_SOURCE));
        }

        // 属性赋值：分页
        resultThroughVO.setPageHelper(indexThroughDTO.getPageHelper());

        // 属性赋值：标题
        UserVO userEntity = resultThroughDTO.getLoginUser();
        Long checkedDepId = resultThroughDTO.getCheckedDepId();
        String checkedUserId = resultThroughDTO.getCheckedUserId();
        CompanyStructTypeEnum companyStructTypeEnum = chartDtoHelp.ifCheckDepOrUser(checkedDepId, checkedUserId,resultThroughDTO.getCheckedDepIdIn(),resultThroughDTO.getCheckedUserIdIn());
        String title;
        switch (companyStructTypeEnum) {
            case USER:
                if (Objects.equals(checkedUserId, userEntity.getUserId())) {
                    title = userEntity.getName();
                    resultThroughVO.setAvatar(userEntity.getAvatar());
                } else {
                    UserEntity checkUser = userModel.getByKeyIngoreDel(checkedUserId, userEntity.getCorpid());
                    if (checkUser == null) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100065, SystemErrorCodeEnum.API_ERROR_100065.getMsg());
                    }
                    title = checkUser.getName();
                    resultThroughVO.setAvatar(checkUser.getAvatar());
                }
                break;
            case DEPARTMENT:
                if (checkedDepId == null || checkedDepId == 1) {
                    title = I18nMessageUtil.getMessage(CommonConstant.COMPANY_WIDE);
                } else {
                    DepartmentEntity departmentEntity = departmentModel.getByKey(checkedDepId, userEntity.getCorpid());
                    if (departmentEntity == null) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100067, SystemErrorCodeEnum.API_ERROR_100067.getMsg());
                    }
                    title = departmentEntity.getName();
                }
                break;
            default:
                title = I18nMessageUtil.getMessage(CommonConstant.COMPANY_WIDE);
                break;
        }
        String startTime = DateUtil.getDateString(resultThroughDTO.getStartTime());
        String endTime = DateUtil.getDateString(resultThroughDTO.getEndTime());
        resultThroughVO.setHead(title + startTime + I18nMessageUtil.getMessage(CommonConstant.TO) + endTime + chartEntity.getName());

        return resultThroughVO;
    }



    /**
     * 处理pc端的数据
     * @param indexThroughDTO 具体的数据
     * @param penetrateAttrMap 表头字段
     * @param resultThroughVO 返回的穿透VO（Web端）
     * @param chartEntity 图表实体
     * @author 梅伟丁
     * @date 2022/3/24 13:52
     * @version 1.0
     */
    private void handleSpecificData4Web(IndexThroughDTO indexThroughDTO, Map<String, JSONObject> penetrateAttrMap, ResultThroughVO resultThroughVO,ChartEntity chartEntity) {
        List<IndexThroughPojo> indexThroughPojoList = indexThroughDTO.getIndexThroughPojoList();
        JSONArray newDataArr = new JSONArray();

        // 具体属性赋值
        indexThroughPojoList.forEach(indexThroughPojo ->{
            JSONObject newDataObj = new JSONObject();
            Integer businessType = indexThroughDTO.getBusinessType();
            Long dataId = indexThroughPojo.getDataId();

            JSONObject data = indexThroughPojo.getData();

            penetrateAttrMap.forEach((key,value)->{
                // 特殊处理，如果是时间类型的将其解析为规定格式
                Integer fieldType = FastJsonHelper.getIntegerOrDefault(value, FieldAttrConstant.FIELD_TYPE, -1);
                // 时间需要格式化
                if (FieldTypeEnum.isDateTimeByFieldType(fieldType)){
                    String dateVar = data.getString(key);
                    String result = StringUtil.isNumeric(dateVar) ? DateTimeUtil.getStringEpochSecond(Long.valueOf(dateVar), DateTimeUtil.SDFDate) : dateVar;
                    newDataObj.put(key, new TableDataInfoPojo(result));
                } else if (Objects.equals(FieldTypeEnum.COMBO.getType(), fieldType) || Objects.equals(FieldTypeEnum.RADIO_GROUP.getType(), fieldType)) {
                    // 下拉框或者单选框需要转换值，而不是显示数字
                    Object object = data.get(key);
                    String typeValue = FastJsonHelper.getValueByFieldType(object);
                    TableDataInfoPojo tableDataInfoPojo = new TableDataInfoPojo(typeValue, BasicConstant.ONE, businessType, dataId, businessType);
                    newDataObj.put(key, tableDataInfoPojo);
                } else if (Objects.equals(FieldTypeEnum.CHECKBOX_GROUP.getType(), fieldType) || Objects.equals(FieldTypeEnum.COMBO_CHECK.getType(), fieldType)) {
                    // 下拉多选或复选框需要转换值，而不是显示数字
                    Object object = data.get(key);
                    String typeValue = FastJsonHelper.getValueByFieldType(object);
                    TableDataInfoPojo tableDataInfoPojo = new TableDataInfoPojo(typeValue, BasicConstant.ONE, businessType, dataId, businessType);
                    newDataObj.put(key, tableDataInfoPojo);
                } else {
                    Object object = data.get(key);
                    String typeValue = FastJsonHelper.getAttrValueByType(object);
                    TableDataInfoPojo tableDataInfoPojo = new TableDataInfoPojo(typeValue, BasicConstant.ONE, businessType, dataId, businessType);
                    newDataObj.put(key, tableDataInfoPojo);
                }

            });
            newDataArr.add(newDataObj);
        });

        // 属性赋值：数据
        resultThroughVO.setData(newDataArr);
    }

    /**
     * 处理移动端的数据
     * @param indexThroughDTO 具体的数据
     * @param penetrateAttrMap 表头字段
     * @param resultThroughVO 返回到VO（App端）
     * @author 梅伟丁
     * @date 2022/3/24 13:57
     * @version 1.0
     */
    private void handleSpecificData4App(IndexThroughDTO indexThroughDTO, Map<String, JSONObject> penetrateAttrMap, ResultThroughVO resultThroughVO) {

        List<IndexThroughPojo> indexThroughPojoList = indexThroughDTO.getIndexThroughPojoList();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(indexThroughDTO.getBusinessType());


        List<AppListPojo> appListPojos = new ArrayList<>();

        // 具体属性赋值
        indexThroughPojoList.forEach(indexThroughPojo -> {
            // 参数
            Long appId = indexThroughPojo.getAppId();
            Long menuId = indexThroughPojo.getMenuId();
            Long formId = indexThroughPojo.getFormId();
            List<SummaryDataPoJo> summaryList = new ArrayList<>();
            List<SummaryDataPoJo> lablesList = new ArrayList<>();
            JSONObject superScript = new JSONObject();
            List<FormTitlePoJo> titleList = new ArrayList<>();
            JSONObject others = new JSONObject();

            JSONObject data = indexThroughPojo.getData();

            // 对于移动端特殊表单的特殊处理
            switch (xbbRefTypeEnum){
                case PRODUCT:
                    formatProduct4App(indexThroughPojo,superScript,lablesList,others);
                    break;
                case PAYMENT:
                    formatPayment4App(indexThroughPojo,superScript,lablesList,others);
                    break;
                case PAYMENT_SHEET:
                    formatPaymentSheet4App(indexThroughPojo,superScript,lablesList,others);
                    break;
                case CONTRACT:
                    formatContract4App(indexThroughPojo,superScript,lablesList,others);
                    break;
                default:
                    break;
            }
            // 插入具体数据
            penetrateAttrMap.forEach((key,value)->{
                Integer fieldType = FastJsonHelper.getIntegerOrDefault(value, FieldAttrConstant.FIELD_TYPE, -1);
                // 时间需要格式化
                if (FieldTypeEnum.isDateTimeByFieldType(fieldType)){
                    String dateVar = data.getString(key);
                    String result = StringUtil.isNumeric(dateVar) ? DateTimeUtil.getStringEpochSecond(Long.valueOf(dateVar), DateTimeUtil.SDFDate) : dateVar;
                    summaryList.add(commonHelp.setSummary(value.get(StringConstant.ATTR_NAME).toString(),result));
                }else {
                    summaryList.add(commonHelp.setSummary(value.get(StringConstant.ATTR_NAME).toString(),FastJsonHelper.getAttrValueByType(data.get(key))));
                }
            });
            // 设置标题
            titleList.add(commonHelp.setTitle(indexThroughPojo.getSerialNo()));
            // 属性赋值
            appListPojos.add(new AppListPojo(indexThroughPojo.getId(), titleList, summaryList, superScript, lablesList, others, appId, menuId, formId));
        });

        ListAppVO listAppVo = new ListAppVO(appListPojos, appListPojos.size());
        resultThroughVO.setBusinessType(indexThroughDTO.getBusinessType());
        resultThroughVO.setDataApp(listAppVo);
    }

    /**
     * 移动端"合同"处理穿透后的显示问题，上角标，摘要数据，其他（右上角，右下角等特殊位置）
     * @param indexThroughPojo 具体穿透实体
     * @param superScript 上角标
     * @param lablesList 摘要数据
     * @param others 其他（右上角，右下角等特殊位置）
     * @author 梅伟丁
     * @date 2022/4/6 18:18
     * @version 1.0
     */
    private void formatContract4App(IndexThroughPojo indexThroughPojo, JSONObject superScript, List<SummaryDataPoJo> lablesList, JSONObject others) {
        JSONObject data = indexThroughPojo.getData();
        //获取启用的合同状态
        String status = data.getString(ContractEnum.STATUS.getAttr());
        lablesList.add(commonHelp.setLable(ContractEnum.STATUS.getAttrName(), status));
        /*-- 其他 -*/
        double amountDouble = data.getDoubleValue(ContractEnum.AMOUNT.getAttr());
        String amount = StringUtil.formatDouble(amountDouble);
        Integer isRed = (Integer) data.getOrDefault(ContractEnum.IS_RED.getAttr(), 0);
        others.put("amount", amount);
        others.put("isRed", isRed);
    }

    /**
     * 移动端"回款单"处理穿透后的显示问题，上角标，摘要数据，其他（右上角，右下角等特殊位置）
     * @param indexThroughPojo 具体穿透实体
     * @param superScript 上角标
     * @param lablesList 摘要数据
     * @param others 其他（右上角，右下角等特殊位置）
     * @author 梅伟丁
     * @date 2022/4/6 16:40
     * @version 1.0
     */
    private void formatPaymentSheet4App(IndexThroughPojo indexThroughPojo, JSONObject superScript, List<SummaryDataPoJo> lablesList, JSONObject others) {
        JSONObject data = indexThroughPojo.getData();
        String typeCode = data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr());
        String typeName = PaymentSheetTypeEnum.getByName(typeCode).getName();
        Double amountDouble = FundHelp.getSheetAmount4PaymentSheet(data, typeCode);
        String amount = StringUtil.formatDouble(amountDouble);
        amount = amount + UnitEnum.MONEY.getName();
        others.put("amount", amount);
        others.put("status", typeName);
        //处理红冲和坏账状态
        boolean red = PaymentSheetTypeEnum.isRed(typeCode);
        int redStatus = red ? 1 : 0;
        boolean bad = PaymentSheetTypeEnum.isBad(typeCode);
        int badStatus = bad ? 1 : 0;
        others.put("isRed", redStatus);
        others.put("isBad", badStatus);
    }

    /**
     * 移动端"应收款"处理穿透后的显示问题，上角标，摘要数据，其他（右上角，右下角等特殊位置）
     * @param indexThroughPojo 具体穿透实体
     * @param superScript 上角标
     * @param lablesList 摘要数据
     * @param others 其他（右上角，右下角等特殊位置）
     * @author 梅伟丁
     * @date 2022/4/6 16:10
     * @version 1.0
     */
    private void formatPayment4App(IndexThroughPojo indexThroughPojo, JSONObject superScript, List<SummaryDataPoJo> lablesList, JSONObject others) {
        double amount = indexThroughPojo.getData().getDoubleValue(PaymentEnum.AMOUNT.getAttr());
        Double realAmount = indexThroughPojo.getData().getDoubleValue(PaymentEnum.REAL_AMOUNT.getAttr());
        if (realAmount < 0) {
            amount = realAmount;
        }
        String amountStr = StringUtil.formatDouble(amount);

        String statusStr = indexThroughPojo.getData().getString(PaymentEnum.STATUS.getAttr());

        String status = PaymentStatusEnum.getByAlias(statusStr).getAlias();
        Integer isRed = (Integer) indexThroughPojo.getData().getOrDefault(PaymentEnum.IS_RED.getAttr(), 0);
        Integer isBad = 0;
        if ( Objects.equals(PaymentStatusEnum.getByAlias(status),PaymentStatusEnum.BAD_DEBT) ){
            isBad = 1;
        }
        commonHelp.setPaymentOthers(others, amountStr, status, isRed, isBad);
    }

    /**
     * 移动端产品模块处理穿透后的显示问题，上角标，摘要数据，其他（右上角，右下角等特殊位置）
     * @param indexThroughPojo 具体穿透实体
     * @param superScript 上角标
     * @param lablesList 摘要数据
     * @param others 其他（右上角，右下角等特殊位置）
     * @author 梅伟丁
     * @date 2022/4/6 10:13
     * @version 1.0
     */
    private void formatProduct4App(IndexThroughPojo indexThroughPojo, JSONObject superScript, List<SummaryDataPoJo> lablesList, JSONObject others) {
        JSONObject data = indexThroughPojo.getData();
        // 获取产品图片，若有插入图片，若无插入空串
        Object productImgs = data.get(ProductEnum.PRODUCT_IMGS.getAttr());
        if (productImgs == null){
            productImgs = "";
        }
        others.put(ProductEnum.PRODUCT_IMGS.getSaasAttr(), productImgs);
    }

    /**
     * 处理须返回的表头字段
     * @param headList 原始表头字段
     * @param penetrateAttrMap 自定义表头字段
     * @author xinpeng.jiang
     * @date 2022/3/23 15:30
     * @version 1.0
     * @return 处理完pojo
     */
    private List<TitlePojo> handleHeadList(List<FieldAttrEntity> headList, Map<String, JSONObject> penetrateAttrMap) {
        List<TitlePojo> titlePojoList = new ArrayList<>();
        for (FieldAttrEntity fieldAttrEntity : headList) {
            if (penetrateAttrMap.containsKey(fieldAttrEntity.getAttr())) {
                TitlePojo titlePojo = new TitlePojo(fieldAttrEntity.getAttr(),fieldAttrEntity.getAttrName(),fieldAttrEntity.getFieldType());
                titlePojoList.add(titlePojo);
                // 处理完所有字段跳出循环
                if (titlePojoList.size() >= penetrateAttrMap.size()) {
                    break;
                }
            }
        }
        return titlePojoList;
    }
}
